package positioncysand.wk;

import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.content.BroadcastReceiver;
import positioncysand.wk.GPSData;

import positioncysand.wk.R;
import positioncysand.wk.HTService;




public class HTService extends Activity  implements Runnable
{
	private static final String TAG = "HTService";
	private LocationManager mLocationManager = null;
	private TelephonyManager mTelephoneManager = null;
	private static final int LOCATION_INTERVAL = 10000;
	//private static final float LOCATION_DISTANCE = 5.0f;
	private static final float LOCATION_DISTANCE = 0;
	////////////////// UPDATE TELA /////////////////
	//GPSData objGPSDataClass=new GPSData();
	//GPSData objGPSDataClass;
	public double dbLat=0;
	public double dbLon=0;
	public double dbAlt=0;
	public float flSpeed=0;
	public String strLevelbat=null;
	String Imei;
	
	Context appContext;
	
	public class LocationListener implements android.location.LocationListener{
	    Location mLastLocation;
	    
	   // String Email;
	    public LocationListener(String provider)
	    {
	    	
	        Log.e(TAG, "[LocationListener] LocationListener Provider " + provider);				//DEBUG
	        mLastLocation = new Location(provider);        
	    }
	    /////////////////////////////////////////////////////////////// ONLOCATION CHANGED ///////////////////////////
	    public void onLocationChanged(Location location)
	    {
	    	
	    	Socket sock = null;    	
	       // Log.i(TAG, "[onLocationChanged] onLocationChanged: " + location);					//DEBUG
	        mLastLocation.set(location);
	        
	   	  try
	   	  {
	   		  SharedPreferences settings = getSharedPreferences("HT",MODE_PRIVATE);
	
		   		  Log.i(TAG,"[onLocationChanged] Enviando datos a Server "+"190.18.128.130 : 5123");			//DEBUG
		   		sock = new Socket("190.18.128.130",5123);
		   		   		 
		   		  Log.i(TAG,"[onLocationChanged] CONEXION SOCKET CREADA ");			//DEBUG   		
		   		Log.i(TAG,"[onLocationChanged] SOCKET IP: "+String.valueOf(sock.getLocalPort()));			//DEBUG
		   		Log.i(TAG,"[onLocationChanged] SOCKET PORT: "+String.valueOf(sock.getLocalPort()));			//DEBUG
		   		Log.i(TAG,"[onLocationChanged] SOCKET IS CONNECTED?: "+String.valueOf(sock.isConnected()));			//DEBUG
		   		//Log.i(TAG,"[onLocationChanged] SOCKET ADDRESS Local: "+String.valueOf(sock.getLocalSocketAddress()));			//DEBUG	   		
		   		Log.i(TAG,"[onLocationChanged] SOCKET ADDRESS Remote: "+String.valueOf(sock.getRemoteSocketAddress()));			//DEBUG
		   		
		   		 dbLat=location.getLatitude();
		   		 dbLon=location.getLongitude();
		   		 dbAlt=location.getAltitude();
		   		 flSpeed=location.getSpeed();
		   		
		   		  String test = "{"
		   				  		+ "\"Id\":\""+"AndCYS"+"\","
		   				  		+ "\"Lat\":\""+String.valueOf(dbLat)+"\","
		   				  		+ "\"Lng\":\""+String.valueOf(dbLon)+"\","
		   				  		+ "\"Alt\":\""+String.valueOf(dbAlt)+"\","
		   				  		+ "\"Spe\":\""+String.valueOf(flSpeed)+"\","						
		   				  		+ "\"IMEI\":\""+Imei+"\","
		   				  		+ "\"CodAct\":\""+settings.getString("CodeActiv",null)+"\","
		   				  		+ "\"Batt\":\""+ strLevelbat+"\""
		   		  				+ "}";
		   		  
		   		  Log.i(TAG,"[onLocationChanged] Stream enviado: "+test);					//DEBUG
		   		  
		   		  sock.getOutputStream().write(test.getBytes());
		   		  sock.close();  			   		
	   	  }
	   	  catch(Exception ex)
	   	  {
	   	      Log.e(TAG, " [onLocationChanged] Error enviando al socket: "+ex.getMessage());			//DEBUG   	     
	   	      try {
				sock.close();
			  }catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	   	  }
	   	  
	   	  try
	   	  {
	   		//objPositioncys.updateCoordinates(dbLat,dbLon,dbAlt,flSpeed,Imei,strLevelbat);
	   	  }catch(Exception ex)
	   	  {
	   		  Log.i(TAG,"[onLocationChanged] ERROR Update Coordenadas en TELA: "+ex );
	   	  }
	    }
	    public void onProviderDisabled(String provider)
	    {
	        Log.e(TAG, "[onProviderDisabled] onProviderDisabled: " + provider);					//DEBUG            
	    }
	    public void onProviderEnabled(String provider)
	    {
	        Log.e(TAG, "[onProviderEnabled] onProviderEnabled: " + provider);					//DEBUG
	    }
	    public void onStatusChanged(String provider, int status, Bundle extras)
	    {
	        Log.e(TAG, "[onStatusChanged] onStatusChanged: " + provider);						//DEBUG
	    }
	} 
	LocationListener[] mLocationListeners = new LocationListener[] {
	        new LocationListener(LocationManager.GPS_PROVIDER),
	        new LocationListener(LocationManager.NETWORK_PROVIDER)
	};
	
	public String strbatteryLevel() {
		
		BroadcastReceiver batteryLevelReceiver = new BroadcastReceiver() {
			
			public void onReceive(Context context, Intent intent) {
		
				context.unregisterReceiver(this);
			
				int rawlevel = intent.getIntExtra("level", -1);
			
				int scale = intent.getIntExtra("scale", -1);
			
				int levelbat = -1;
			
				if (rawlevel >= 0 && scale > 0) {
			
					levelbat = (rawlevel * 100) / scale;
			
				}
				Log.i(TAG, "[strbatteryLevel] BATTERY int: " + levelbat);
				strLevelbat=String.valueOf(levelbat);
				Log.i(TAG, "[strbatteryLevel] BATTERY str: " + strLevelbat);	
			}
			
		};
		
		IntentFilter batteryLevelFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);    	
		registerReceiver(batteryLevelReceiver, batteryLevelFilter);
		Log.i(TAG, "[strbatteryLevel] BATTERY str final: " + strLevelbat);	
		
		return strLevelbat;
	}
	/*
	public IBinder onBind(Intent arg0)
	{
	    return null;
	}
	
	public int onStartCommand(Intent intent, int flags, int startId)
	{    
		Log.e(TAG, "[onStartCommand] onStartCommand");							//DEBUG
	    super.onStartCommand(intent, flags, startId);       
	    return START_STICKY;
	}
	*/
	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		Log.e(TAG, "[onCreate] onCreate");		
		try
		{			
			/////////////////
			 super.onCreate(savedInstanceState);			
		     setContentView(R.layout.viewsender);	     
		     appContext = this.getApplicationContext();
		     ///////////////
		     
		     Thread currentThread = new Thread(this);
		     currentThread.start();
		     
			 int inTiempoEnvio=0;
		    							//DEBUG
		    SharedPreferences settings = getSharedPreferences("HT",MODE_PRIVATE);	    
		    try
		    {
			    initializeLocationManager();
			    
			     inTiempoEnvio=Integer.valueOf(settings.getString("Timer",null))*1000;
		    }catch(Exception ex)
		    {
		    	Log.e(TAG, "[onCreate] ERROR: "+ex);		
		    	//settings.edit().clear();
		    }
		    try {
		        
		    	/*mLocationManager.requestLocationUpdates(
		    			LocationManager.NETWORK_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE,
		    			mLocationListeners[1]);
		    	*/
		    	if((inTiempoEnvio!=0))
		    	{
		    		mLocationManager.requestLocationUpdates(	    	
		    			LocationManager.NETWORK_PROVIDER, inTiempoEnvio, LOCATION_DISTANCE,
		    			mLocationListeners[1]);
		    	}else
		    	{
		    		mLocationManager.requestLocationUpdates(	    	
			    			LocationManager.NETWORK_PROVIDER,2, LOCATION_DISTANCE,
			    			mLocationListeners[1]);
		    	}
		    	Log.d(TAG, "[onCreate] Pase REQUEST_LOCATION_UPDATES");		//DEBUG    	
		        
		    	strLevelbat=strbatteryLevel();        
		        Imei = mTelephoneManager.getDeviceId();
		        
		        
		    } catch (java.lang.SecurityException ex) {
		        Log.i(TAG, "[onCreate] fail to request location update, ignore", ex);		//DEBUG
		    } catch (IllegalArgumentException ex) {
		        Log.d(TAG, "[onCreate] network provider does not exist, " + ex.getMessage());		//DEBUG        
		    }
		    try {
		        
		    	if((inTiempoEnvio!=0))
		    	{
		    		mLocationManager.requestLocationUpdates(	    	
		    			LocationManager.GPS_PROVIDER, inTiempoEnvio, LOCATION_DISTANCE,
		    			mLocationListeners[0]);
		    	}else
		    	{
		    		mLocationManager.requestLocationUpdates(	    	
			    			LocationManager.GPS_PROVIDER,2, LOCATION_DISTANCE,
			    			mLocationListeners[0]);
		    	}
		    	Log.d(TAG, "[onCreate] Pase REQUEST_LOCATION_UPDATES 2 DOS");		//DEBUG
		    	
		        Imei = mTelephoneManager.getDeviceId();      
		        strLevelbat=strbatteryLevel();
		        
		        ///////////////////////////// TIMER //////////////////////////
		        /*try
				{
		        	Log.i("HTService","Durmiendo el tiempo configurado TIME: "+settings.getString("Timer",null));
					Thread.sleep(Integer.valueOf(settings.getString("Timer",null))*1000,0);
				}
				catch (InterruptedException e)
				{
					Log.i("HTService","SLEEP ERROR: "+e);
				}*/
		        //objGPSDataClass.updateCoordinates(dbLat,dbLon,dbAlt,flSpeed,Imei,strLevelbat);
		        
		        
		    } catch (java.lang.SecurityException ex) {
		        Log.i(TAG, "[onCreate] fail to request location update, ignore", ex);			//DEBUG
		    } catch (IllegalArgumentException ex) {
		        Log.d(TAG, "[onCreate] gps provider does not exist " + ex.getMessage());			//DEBUG
		    } 
		}catch(Exception EX)
		{
			Log.e(TAG, "[onCreate]ERROR " + EX.getMessage());			//DEBUG
			Log.e(TAG, "[onCreate]ERROR " + EX);			//DEBUG
		}
	}
	

	@Override
	public void onDestroy()
	{
	     Log.e(TAG, "[onDestroy] onDestroy");								//DEBUG
	    super.onDestroy();
	    if (mLocationManager != null) {
	        for (int i = 0; i < mLocationListeners.length; i++) {
	            try {
	                mLocationManager.removeUpdates(mLocationListeners[i]);
	            } catch (Exception ex) {
	                Log.i(TAG, "[onDestroy] fail to remove location listners, ignore", ex);			//DEBUG
	            }
	        }
	    }
	} 
	public void initializeLocationManager() {
	   Log.e(TAG, "[initializeLocationManager] initializeLocationManager");				//DEBUG
	   
	    if (mLocationManager == null) {
	    	Log.e(TAG, "[initializeLocationManager] mLocationManager == NULL");				//DEBUG
	    	mLocationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
	    }
	    if (mTelephoneManager == null)
	    {
	    	Log.e(TAG, "[initializeLocationManager] mTelephoneManager==NULL");				//DEBUG
	    	mTelephoneManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
	    }
	}

	public void run() {
		// TODO Auto-generated method stub
		Log.i(TAG, "[run] Run");									//DEBUG
		try
		{
			startUpdateCoordinates();
			
		}catch(Exception Ex)
		{
			Log.e(TAG, "[run] Error: " +Ex.getMessage());									//DEBUG
		}
		    
	}
	
	public void startUpdateCoordinates()
	{	
		 int inTiempoEnvio=0;
		    Log.e(TAG, "[onCreate] onCreate");									//DEBUG
		    SharedPreferences settings = getSharedPreferences("HT",MODE_PRIVATE);	    
		    try
		    {
			    initializeLocationManager();
			    
			     inTiempoEnvio=Integer.valueOf(settings.getString("Timer",null))*1000;
		    }catch(Exception ex)
		    {
		    	Log.e(TAG, "[onCreate] ERROR: "+ex);		
		    	//settings.edit().clear();
		    }
		    try {
		        
		    	/*mLocationManager.requestLocationUpdates(
		    			LocationManager.NETWORK_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE,
		    			mLocationListeners[1]);
		    	*/
		    	if((inTiempoEnvio!=0))
		    	{
		    		mLocationManager.requestLocationUpdates(	    	
		    			LocationManager.NETWORK_PROVIDER, inTiempoEnvio, LOCATION_DISTANCE,
		    			mLocationListeners[1]);
		    	}else
		    	{
		    		mLocationManager.requestLocationUpdates(	    	
			    			LocationManager.NETWORK_PROVIDER,2, LOCATION_DISTANCE,
			    			mLocationListeners[1]);
		    	}
		    	Log.d(TAG, "[onCreate] Pase REQUEST_LOCATION_UPDATES");		//DEBUG    	
		        
		    	strLevelbat=strbatteryLevel();        
		        Imei = mTelephoneManager.getDeviceId();
		        
		        
		    } catch (java.lang.SecurityException ex) {
		        Log.i(TAG, "[onCreate] fail to request location update, ignore", ex);		//DEBUG
		    } catch (IllegalArgumentException ex) {
		        Log.d(TAG, "[onCreate] network provider does not exist, " + ex.getMessage());		//DEBUG        
		    }
		    try {
		        
		    	if((inTiempoEnvio!=0))
		    	{
		    		mLocationManager.requestLocationUpdates(	    	
		    			LocationManager.GPS_PROVIDER, inTiempoEnvio, LOCATION_DISTANCE,
		    			mLocationListeners[0]);
		    	}else
		    	{
		    		mLocationManager.requestLocationUpdates(	    	
			    			LocationManager.GPS_PROVIDER,2, LOCATION_DISTANCE,
			    			mLocationListeners[0]);
		    	}
		    	Log.d(TAG, "[onCreate] Pase REQUEST_LOCATION_UPDATES 2 DOS");		//DEBUG
		    	
		        Imei = mTelephoneManager.getDeviceId();      
		        strLevelbat=strbatteryLevel();
		        
		        ///////////////////////////// TIMER //////////////////////////
		       try
				{
		        	Log.i("HTService","Durmiendo el tiempo configurado TIME: "+settings.getString("Timer",null));
					Thread.sleep(Integer.valueOf(settings.getString("Timer",null))*1000,0);
				}
				catch (InterruptedException e)
				{
					Log.i("HTService","SLEEP ERROR: "+e);
				}
		        //objGPSDataClass.updateCoordinates(dbLat,dbLon,dbAlt,flSpeed,Imei,strLevelbat);
		        
		        
		    } catch (java.lang.SecurityException ex) {
		        Log.i(TAG, "[onCreate] fail to request location update, ignore", ex);			//DEBUG
		    } catch (IllegalArgumentException ex) {
		        Log.d(TAG, "[onCreate] gps provider does not exist " + ex.getMessage());			//DEBUG
		    }
		  //  return true;
	}
	
	protected void onStop() {
		
		super.onStop();
	}
	
}
